//
//  CXLComposeViewController.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/24.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 发布微博视图
class CXLComposeViewController: UIViewController {

    
    //MARK: - 监听方法
    ///  关闭按钮
    @objc private func close(){
        
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///  发布微博
    @objc private func sendStatus(){
    
        let image = picturePickerViewController.pictrues.last
        
        CXLAFNMangerTool.sharedAFNMangerTool.updateStatus(textView.emoticonText, image: image) { (result, error) -> () in
            
            if error != nil{
                
                SVProgressHUD.showInfoWithStatus("网络有误")
                
                return
            }
            
            print("发布成功")
            
            SVProgressHUD.showInfoWithStatus("发布成功")
            
            self.close()
        }
    }
    
    ///  选择表情键盘
    @objc private func selectEmoticon(){
        //取消键盘
        textView.resignFirstResponder()
        //设置键盘
        textView.inputView =  (textView.inputView == nil) ? emoticonView :nil
        
        textView.becomeFirstResponder()
    }
    
    ///  选择 图片选择
    @objc private func selectPicturePicker(){
        
        if picturePickerViewController.view.frame.height > 0{
            
            print("已经选择了")
            
            return
        }
        
        textView.resignFirstResponder()
        
        picturePickerViewController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerViewController.view.snp_top)
        }
    }
    
    ///  监听键盘的弹出
    @objc private func boardWillChangeFrame(notify:NSNotification){
        
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        let duration = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        let curve = (notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        UIView.animateWithDuration(duration) { () -> Void in
            // 设置动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
    }
    
    //:MARK: - 视图生命周期
    override func loadView() {
        
        view = UIView()
        
        setupUI()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerViewController.view.frame.height == 0 {
            
            textView.becomeFirstResponder()
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册通知中心
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "boardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        addChildViewController(picturePickerViewController)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //MARK: -懒加载
    /// 工具条
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    /// 输入视图
    private lazy var textView:UITextView = {
    
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        
        // textView 下拉弹簧
        tv.alwaysBounceVertical = true
        
        //下拉退出键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.delegate = self
        
        return tv
    }()
    
    /// 表情键盘
    private lazy var emoticonView:CXLEmotionView = CXLEmotionView {[weak self] (emoticon) -> () in
        
        self?.textView.loadTextViewText(emoticon)
    }
    
    /// 站位label
    private lazy var holderLbl:UILabel = UILabel(titleText: "分享新鲜事.....", textFont: 18, color: UIColor.lightGrayColor())
    
    /// 图片选择控制器
    private lazy var picturePickerViewController:CXLPicturePickerViewController = CXLPicturePickerViewController()
}

// MARK: - textView的代理方法
extension CXLComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        holderLbl.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled =  textView.hasText()
        
    }

}

// MARK: - 设置UI界面
extension CXLComposeViewController {
    
    ///  设置UI界面
    private func setupUI(){
        
        self.automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.lightGrayColor()

        prepareForNavigationBar()
        
        prepareForToolBar()
        
        prepareForTextView()
        
        prepareForPicturePickerView()
    }
    
    ///  图片选择视图
    private func prepareForPicturePickerView(){

        view.insertSubview(picturePickerViewController.view, belowSubview: toolBar)
        
        picturePickerViewController.view.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view.snp_right)
            make.left.equalTo(view.snp_left)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(0)
        }
    }
    
    ///  输入视图
    private func prepareForTextView(){
        
        //添加视图
        view.addSubview(textView)
    
        textView.textColor = UIColor.redColor()
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        textView.addSubview(holderLbl)
        
        holderLbl.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(6)
            make.top.equalTo(textView.snp_top).offset(7)
        }
        
    }
    
    ///  设置工具栏
    private func prepareForToolBar(){
        //添加控键
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        //自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
            make.bottom.equalTo(view.snp_bottom)
        }
        
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName" : "selectPicturePicker"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName" : "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()

        toolBar.items = items
    }
    
    ///  设置导航栏
    private func prepareForNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        
        navigationItem.titleView = titleView
        
        let titleLbl:UILabel = UILabel(titleText: "发微博", textFont: 15)
        let nameLbl:UILabel = UILabel(titleText:OauthViewModel.sharedOauthViewModel.oauthModel!.screen_name!, textFont: 13, color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLbl)
        titleView.addSubview(nameLbl)
        
        titleLbl.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLbl.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}